package reflect;

import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 调用方法
 */
public class ReflectDemo5 {
    public static void main(String[] args)throws Exception {
        //调用Person类的sayHello方法
        Person p = new Person();
        p.sayHello();

        //反射机制
       /*
        Class cls = Class.forName("reflect.Person");
        Object obj = cls.newInstance();//new Person()
        //获取对应的方法对象
        Method method = cls.getMethod("sayHello");//sayHello()
        method.invoke(obj);//obj.sayHello()
//        method.invoke(p);//p.sayHello()
        */
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入类名:");
        String className = scanner.nextLine();
        System.out.println("请输入方法名:");
        String methodName = scanner.nextLine();

        Class cls = Class.forName(className);
        Object obj = cls.newInstance();

        Method method = cls.getMethod(methodName);
        method.invoke(obj);

    }
}
